package com.core.service;

import com.alibaba.fastjson.JSON;
import com.core.dto.MockDto;
import com.core.mapper.MockMapper;
import com.core.vo.MockVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * create by yongli on 2021-09-16 19:32
 */
@Service
public class MockService {
    private final Logger logger = LoggerFactory.getLogger(MockService.class);
    @Autowired
    MockMapper mockMapper;

    public int insert(MockVo mockVo) {

        // 在插入时保证param唯一
        MockDto mockDto = mockMapper.selectByParam(mockVo.getParam());
        if (mockDto != null) {
            BeanUtils.copyProperties(mockVo, mockDto);
            mockMapper.update(mockDto);
            return 1;
        }
        mockDto = new MockDto();
        BeanUtils.copyProperties(mockVo, mockDto);
        return mockMapper.insert(mockDto);
    }

    public MockVo selectByParam(String param) {

        MockDto mockDto = mockMapper.selectByParam(param);
        if (mockDto == null) {
            return new MockVo();
        }
        logger.info("select 结果：" + JSON.toJSONString(mockDto));
        MockVo mockVo = new MockVo();
        // soure must not be null
        BeanUtils.copyProperties(mockDto, mockVo);
        return mockVo;
    }
}
